/**
 * @desc: 编辑规格
 * @author: fj
 */

import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import CommonTable from '@/components/CommonTable';
import CommonZjfImg from '@/components/CommonImg/ZifComponent';
import CommonSysImg from '@/components/CommonImg/SysComponent';
import { cloneDeep, isEmpty, findIndex } from 'lodash';
import { getSpecList, getSysSpecList } from '../service';
import { Button, Select, Checkbox, message } from 'antd';
import styles from './GoodsList.module.less';

const EditGoodsModal = ({
  visible,
  type,
  recordData,
  handleCancel,
  handleOk,
}) => {
  const [goodsList, setGoodsList] = useState([]);
  const [allChecked, setAllChecked] = useState(true); //全选状态
  const [loading, setLoading] = useState(false);

  const columns = [
    //供应商列表
    {
      title: (
        <>
          <Checkbox
            onChange={(e) => changeAllChecked(e.target.checked)}
            checked={allChecked}
            disabled={isEmpty(goodsList)}
            className={styles.marginRight10}
          />
          尺码
        </>
      ),
      dataIndex: 'size',
      key: 'size',
      width: 220,
      render: (text, { sizeChecked }, index) => {
        return (
          <>
            <Checkbox
              onChange={(e) => changeSize(e.target.checked, index)}
              checked={sizeChecked}
              className={styles.marginRight10}
            />
            {text}
          </>
        );
      },
    },
    {
      title: '颜色',
      dataIndex: 'colorArr',
      key: 'colorArr',
      width: 480,
      render: (text, { colorArr = [] }, index) => {
        return (
          <div style={{ display: 'flex', flexWrap: 'wrap' }}>
            {colorArr.map((item, indexs) => {
              return (
                <span key={item.goodsId}>
                  <Checkbox
                    checked={item.colorChecked}
                    style={{ marginRight: 24 }}
                    onChange={(e) =>
                      changeColor(e.target.checked, index, indexs)
                    }
                  >
                    {item.color}
                  </Checkbox>
                </span>
              );
            })}
          </div>
        );
      },
    },
  ];

  const columns2 = [
    //系统列表
    {
      title: (
        <>
          <Checkbox
            onChange={(e) => changeAllChecked(e.target.checked)}
            checked={allChecked}
            disabled={isEmpty(goodsList)}
            className={styles.marginRight10}
          />
          尺码
        </>
      ),
      dataIndex: 'size',
      key: 'size',
      width: 220,
      render: (text, { sizeChecked }, index) => {
        return (
          <>
            <Checkbox
              onChange={(e) => changeSize(e.target.checked, index)}
              checked={sizeChecked}
              className={styles.marginRight10}
            />
            {text}
          </>
        );
      },
    },
    {
      title: '颜色+其他属性',
      dataIndex: 'colorArr',
      key: 'colorArr',
      width: 480,
      render: (text, { colorArr = [] }, index) => {
        return (
          <div style={{ display: 'flex', flexWrap: 'wrap' }}>
            {colorArr.map((item, indexs) => {
              return (
                <span key={item.id}>
                  <Checkbox
                    checked={item.colorChecked}
                    style={{ marginRight: 24 }}
                    onChange={(e) =>
                      changeColor(e.target.checked, index, indexs)
                    }
                  >
                    {item.customAtt
                      ? item.colorAtt + ';' + item.customAtt
                      : item.colorAtt}
                  </Checkbox>
                </span>
              );
            })}
          </div>
        );
      },
    },
  ];

  useEffect(() => {
    if (visible) {
      getGoodsList();
    }
  }, [visible]);

  //尺码规格
  const changeSize = (checked, index) => {
    const addDataSource = cloneDeep(goodsList);
    addDataSource[index].sizeChecked = checked;
    const newArr = [];
    addDataSource[index].colorArr.map((item) => {
      newArr.push({
        ...item,
        colorChecked: checked,
      });
    });
    addDataSource[index].colorArr = newArr;
    setGoodsList(addDataSource);
    const size_no = addDataSource.some((item) => item.sizeChecked == false);
    if (size_no) {
      setAllChecked(false);
    } else {
      setAllChecked(true);
    }
  };

  //颜色
  const changeColor = (checked, index, indexs) => {
    const addDataSource = cloneDeep(goodsList);
    addDataSource[index].colorArr[indexs].colorChecked = checked;
    if (checked) {
      const color_no = addDataSource[index].colorArr.some(
        (item) => item.colorChecked == false
      );
      if (color_no) {
        addDataSource[index].sizeChecked = false;
        setAllChecked(false);
      } else {
        addDataSource[index].sizeChecked = true;
        const size_no = addDataSource.some((item) => item.sizeChecked == false);
        if (size_no) {
          setAllChecked(false);
        } else {
          setAllChecked(true);
        }
      }
    } else {
      addDataSource[index].sizeChecked = false;
      setAllChecked(false);
    }
    setGoodsList(addDataSource);
  };

  //全选反全选
  const changeAllChecked = (checked) => {
    const addDataSource = cloneDeep(goodsList);
    addDataSource.map((item) => {
      item.sizeChecked = checked;
      item.colorArr.map((items) => {
        items.colorChecked = checked;
      });
    });
    setGoodsList(addDataSource);
    setAllChecked(checked);
  };

  // 获取所有商品
  const getGoodsList = async () => {
    setLoading(true);
    setGoodsList([]);
    const addDataSource = [];
    if (type == 1) {
      //供应商商品
      const { data = {}, success } = await getSpecList({
        zjfStoreId: recordData.storeId,
        goodsCommonId: recordData.goodsCommonid,
      });
      if (success) {
        Object.keys(data).forEach((item) => {
          //尺码
          const sizeStage = data[item];
          const colorArr = [];
          Object.keys(sizeStage).forEach((items) => {
            //颜色
            const colorStage = sizeStage[items];
            colorStage.map((child) => {
              colorArr.push({
                ...child,
                color: items,
                colorChecked:
                  findIndex(recordData.storeGoodsArr, [
                    'goodsId',
                    child.goodsId,
                  ]) > -1 //已经勾选的颜色
                    ? true
                    : false,
              });
            });
          });
          addDataSource.push({
            size: item,
            sizeChecked: colorArr.some((z) => z.colorChecked == false)
              ? false
              : true, //未全部勾选颜色的时候
            colorArr,
          });
        });
      }
    } else {
      //系统商品
      const { data = {}, success } = await getSysSpecList({
        spuId: recordData.spuId,
      });
      if (success) {
        Object.keys(data).forEach((item) => {
          //尺码
          const sizeStage = data[item];
          const colorArr = [];
          Object.keys(sizeStage).forEach((items) => {
            //颜色
            const colorStage = sizeStage[items];
            colorStage.map((child) => {
              colorArr.push({
                ...child,
                colorChecked:
                  findIndex(recordData.sysGoodsArr, ['id', child.id]) > -1 //已经勾选的颜色
                    ? true
                    : false,
              });
            });
          });
          addDataSource.push({
            size: item,
            sizeChecked: colorArr.some((z) => z.colorChecked == false)
              ? false
              : true, //未全部勾选颜色的时候
            colorArr,
          });
        });
      }
    }
    setGoodsList(addDataSource);
    setAllChecked(
      addDataSource.some((t) => t.sizeChecked == false) ? false : true
    ); //未全部勾选尺码的时候
    setLoading(false);
  };

  //取消
  const onCancel = () => {
    handleCancel();
  };

  //保存进入下一步
  const onSave = () => {
    if (goodsList.length) {
      if (type == 1) {
        //供应商商品
        const arr = [];
        goodsList.map((item) => {
          item.colorArr.map((items) => {
            if (items.colorChecked) {
              arr.push({ ...items });
            }
          });
        });
        if (arr.length) {
          const goodsObj = cloneDeep(recordData); //原本的商品信息
          const colorObj = {}; //去重后商品的颜色
          const sizeObj = {}; //去重后商品的尺寸
          arr.forEach((t, index) => {
            if (!colorObj[t.color]) {
              colorObj[t.color] = {
                colorName: t.color,
                colorNum: 1,
              };
            } else {
              ++colorObj[t.color]['colorNum'];
            }
          });
          arr.forEach((t, index) => {
            if (!sizeObj[t.size]) {
              sizeObj[t.size] = {
                sizeName: t.size,
                sizeNum: 1,
              };
            } else {
              ++sizeObj[t.size]['sizeNum'];
            }
          });
          goodsObj.sizeNum = Object.keys(sizeObj).length;
          goodsObj.colorNum = Object.keys(colorObj).length;
          goodsObj.goodsNum = arr.length;
          goodsObj.storeGoodsArr = arr;
          handleOk(goodsObj);
        } else {
          message.info('请选择尺寸，颜色');
        }
      } else {
        //系统商品
        const sysGoodsArr = [];
        goodsList.map((item) => {
          item.colorArr.map((items) => {
            if (items.colorChecked) {
              sysGoodsArr.push({ ...items });
            }
          });
        });
        if (sysGoodsArr.length) {
          const goodsObj = cloneDeep(recordData); //原本的商品信息
          const colorObj = {}; //去重后商品的颜色
          const sizeObj = {}; //去重后商品的尺寸
          const otherObj = {}; //去重后商品的其他属性
          sysGoodsArr.forEach((t, index) => {
            if (!colorObj[t.colorAtt]) {
              colorObj[t.colorAtt] = {
                colorName: t.colorAtt,
                colorNum: 1,
              };
            } else {
              ++colorObj[t.colorAtt]['colorNum'];
            }
          });
          sysGoodsArr.forEach((t, index) => {
            if (!sizeObj[t.sizeAtt]) {
              sizeObj[t.sizeAtt] = {
                sizeName: t.sizeAtt,
                sizeNum: 1,
              };
            } else {
              ++sizeObj[t.sizeAtt]['sizeNum'];
            }
          });
          sysGoodsArr.forEach((t, index) => {
            if (t.customAtt != '') {
              //过滤空字符串的情况
              if (!otherObj[t.customAtt]) {
                otherObj[t.customAtt] = {
                  otherName: t.customAtt,
                  otherNum: 1,
                };
              } else {
                ++otherObj[t.customAtt]['otherNum'];
              }
            }
          });
          goodsObj.sizeNum = Object.keys(sizeObj).length;
          goodsObj.colorNum = Object.keys(colorObj).length;
          goodsObj.otherNum = Object.keys(otherObj).length;
          goodsObj.goodsNum = sysGoodsArr.length;
          goodsObj.sysGoodsArr = sysGoodsArr;
          handleOk(goodsObj);
        } else {
          message.info('请选择尺寸，颜色');
        }
      }
    }
  };

  //表格props
  const addTableProps = {
    data: goodsList,
    columns: type == 1 ? columns : columns2,
    scroll: { y: 480 },
  };

  return (
    <div>
      <CommonModal
        title={'编辑规格'}
        visible={visible}
        onCancel={onCancel}
        width="848px"
        overflowY="hidden"
        footer={[
          <Button key="back" onClick={onCancel}>
            取消
          </Button>,
          <Button key="save" type="primary" onClick={onSave}>
            保存
          </Button>,
        ]}
      >
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            marginBottom: '20px',
          }}
        >
          {recordData.customType == 'sys' ? (
            <CommonSysImg
              img={recordData.goodsImage}
              storeId={recordData.storeId}
              style={{ marginRight: '8px' }}
            />
          ) : (
            <CommonZjfImg
              img={recordData.goodsImage}
              storeId={recordData.storeId}
              style={{ marginRight: '8px' }}
            />
          )}

          <div style={{ flex: 1 }}>
            <span>{recordData.goodsName}</span>
          </div>
        </div>
        <CommonTable {...addTableProps} />
      </CommonModal>
      <CommonLoading loading={loading} />
    </div>
  );
};

export default React.memo(EditGoodsModal, (pre, next) => {
  if (pre.visible == next.visible) {
    return true;
  } else {
    return false;
  }
});
